Vue.filter('handleTopic', (topicList)=>{
    let topicStr = ""
    if(topicList == undefined){
        return null
    }else{
        topicList.forEach((item)=>{
            topicStr += `#${item}`
        })
        console.log("topicStr")
        console.log(topicStr)
        return topicStr
    }
    
})
Vue.filter('handleLikesIcon', (id)=>{
    return id+'666'
})
Vue.filter('handleTime', (time)=>{
    return time1(time)
    function time1(t) {
        let s  = t.slice(0, 10)
        let year = Number(s.split('/')[0]) 
        let month = Number(s.split('/')[1])
        let day = Number(s.split('/')[2])
        //alert(year+" "+month+" "+day)
        let time1 = getDays(year, month, day) // 目标时间
        let time2 = getDays(vm.now.year, vm.now.month, vm.now.day) //参照时间
        if (year === vm.now.year) {//本年
            if (vm.now.year === year && vm.now.month === month && vm.now.day === day){ //当天
                return t.slice(11, 16) //只返回 时:分
            }else if (vm.now.year === year && time2 - time1 === 1) { //昨天(仅处理同年同月场景)
                return `昨天${t.slice(11, 16)}`  //返回 昨天+时:分
            }else if (vm.now.year === year && time2 - time1 > 1) {
                return t.slice(5, 16) //只返回 月/日 时:分
            }else{ //昨天以前
                return t.slice(5, 16) //只返回 月/日 时:分
            }
        }else{//往年
            return t.slice(0, 16) //返回完整时间 年/月/日 时:分
        } 
    }/**/
    function isfullyear(year){
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return true;
        }
    }
    function getDays(year, month, day){
        //把天数赋值给num
        var num = day;
        //如果用户输入1月 则直接返回天数
        if (month == 1) {
            return day;
        }
        var monthDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        //循环遍历月份 循环条件是用户输入月份的前一个月份 
        for (var i = 0; i < month - 1; i++) {
            //num = 当月天数 + 之前每个月的天数
            num = num + monthDay[i]
        }
        //如果用户输入的年份是闰年并且输入的月份大于2 那么总天数加1
        if (isfullyear(year) && month > 2) {
            num++;
        }
        return num;
    }
})
var vm = new Vue({
    el: 'section',
    data: {
        userid: "",
        userImg: "",
        searchValue: "",
        likesRecords: [],
        allArticleList: [],
        twdt: [],
        tw: [],
        wz: [],
        xq: [],
        page: 1,
        toBottom: false,
        now: {},
        isSearchBoxShow: false,
        //组件
        isLoading: false,
        popupShow: false,
        //组件
        //show: true, //弹窗组件
        show: false, //图片预览组件
        index: 0,
        images: [],
        active: 0, //tabs组件

    },
    methods: {
        SwitchSearchButton(){
            this.searchValue = ""
            document.querySelector(".tem").style.opacity='0'
            document.querySelector(".tem").style.transform='translatex(4.8309rem)' //200px
            let timer1 = setTimeout(()=>{
                this.isSearchBoxShow = !this.isSearchBoxShow
                document.querySelector(".tem").style.transform='translatex(0)'
                document.querySelector(".tem").style.opacity='1'
                clearTimeout(timer1)
            }, 200)
        },
        // checkEnter()
        checkEnter(){
            // console.log(vm.searchValue)
            let input = document.querySelector('.tem input');
            input.addEventListener('keyup', function(event) {
                if (event.keyCode === 13) {
                    vm.search()
                }
            });
        },
        // 搜索事件
        search(){
            console.log(this.searchValue)
            if(/^\s*$/.test(this.searchValue)){
                this.searchValue = ""
                this.$toast({
                    message: "请输入内容！",
                    forbidClick: true
                })
                return
            }
            this.active = "0"
            this.allArticleList = []
            this.page = 1
            this.getLikesRecords()
            // this.active = "0"
        },
        // 点击话题标签搜索事件
        searchTopic(topic){
            
            if(this.isSearchBoxShow){ //搜索框打开状态
                setTimeout(()=>{
                    // document.querySelector(".tem input").value = topic
                    this.searchValue = topic
                    document.querySelector(".tem span").click()
                    

                }, 210)
            }else{ // 搜索框关闭状态
                // 打开搜索框
                document.querySelector(".tem .search").click()
                setTimeout(()=>{
                    // document.querySelector(".tem input").value = topic
                    this.searchValue = topic
                    document.querySelector(".tem span").click()
                }, 210)
            }
            

            // let this.searchValue = topic


        },
        handleScroll(){
            if (!this.toBottom) {
                function isElementInViewport(el) {  
                    const rect = el.getBoundingClientRect();  
                    return rect.top < window.innerHeight && rect.bottom > 0; // 判断元素的上边界小于视口高度，下边界大于0  
                }
                let element = document.querySelector(`.container${this.active} .articleList>li:last-child`); // 获取你要检测的元素

                if (isElementInViewport(element)) {  //元素在可视区域
                    this.toBottom = true
                    //获取新数据
                    console.log("滚动到底部，获取新数据...")

                    let type = ""
                    switch(this.active){
                        case '0':
                            type = "all"
                            break;
                        case '1':
                            type = "twdt"
                            break;
                        case '2':
                            type = "tw"
                            break;
                        case '3':
                            type = "wz"
                            break;
                        case '4':
                            type = "xq"
                            break;
                        default: 
                            type = type
                    }

                    
                    console.log("vm.searchValue: ")
                    console.log(vm.searchValue)
                    vm.getArticles(type, vm.page, vm.searchValue)
                }else{
                    this.toBottom = false
                }
            }    
        },
        //获取本人喜欢列表
        getLikesRecords(){
            //let userInfo = localStorage.getItem('XGB-user')
            //vm.userid = JSON.parse(userInfo).id
            //fetch(`https://fc-mp-e8e2bde5-0c0c-4622-87b5-66f8b08c3856.next.bspapp.com/getArticleList1.0/getLikesRecords_5A4C53v4ced654?userid=${vm.userid}`)
            fetch(`https://fc-mp-e8e2bde5-0c0c-4622-87b5-66f8b08c3856.next.bspapp.com/getArticleList1.0/getLikesRecords_5A4C53v4ced654?userid=${this.userid}`)
                .then(res=> res.json())
                .then(res=>{
                    if(res.code === 0) {
                        console.log(res)
                        console.log(res.data)
                        vm.likesRecords = res.data
                        //获取文章 根据当期页面active来动态改变获取文章的类型
                        let type = ""
                        switch(this.active){
                            case '0':
                                type = "all"
                                break;
                            case '1':
                                type = "twdt"
                                break;
                            case '2':
                                type = "tw"
                                break;
                            case '3':
                                type = "wz"
                                break;
                            case '4':
                                type = "xq"
                                break;
                            default: 
                                type = type
                        }
                        //vm.searchValue = vm.searchValue = undefined ? "" : vm.searchValue
                        console.log("vm.searchValue: ")
                        console.log(vm.searchValue)
                        vm.getArticles(type, vm.page, vm.searchValue)
                    }
                })
        },
        //获取文章
        getArticles(type, page, searchValue){
            /*
            let userInfo = localStorage.getItem('XGB-user')
            this.userid = JSON.parse(userInfo).id
            this.userImg = JSON.parse(userInfo).userImg
            */

            console.log("vm.searchValue: ")
            console.log(vm.searchValue)
                fetch(`https://fc-mp-e8e2bde5-0c0c-4622-87b5-66f8b08c3856.next.bspapp.com/getArticleList1.0/getAllArticles?userid=${this.userid}&type=${type}&page=${page}&search=${encodeURIComponent(searchValue)}`)
                .then(res=> res.json())
                .then(res=>{
                    console.log(res)
                    console.log(res.data)
                    if (res.code === 0) {
                        let data1 = res.data
                        let data2 = data1.map((element, index) => {
                            if (vm.likesRecords.includes(element._id)){
                                return {
                                    ...element,
                                    isLike: true
                                }
                            } else {
                                return {
                                    ...element,
                                    isLike: false
                                }
                            }
                            
                          });
                          console.log("data2")
                          console.log(data2)
                        this.allArticleList = this.allArticleList.concat(data2)
                        console.log("当前是第"+this.page+"页")
                        this.page++
                        this.toBottom = false
                        if (this.page === 2) {
                            this.$toast('刷新成功');
                            this.isLoading = false;
                        }

                    }     
                })
            
        },

        handleSelect (k) {
                let tost1 = this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
            let loading = setTimeout(()=>{
                tost1.clear()
                switch (k) {
                    case 1:
                        location.href='./pages/fbdt/fbdt.html'
                        break
                    case 2:
                        location.href='./pages/fbtw/fbtw.html'
                        break
                    case 3:
                        location.href='./pages/fbwz/fbwz.html'
                        break
                    case 4:
                        location.href='./pages/fbxq/fbxq.html'
                        break
                    default:
                        //文字提示
                        this.$toast('功能开发中...');
                }
                clearTimeout(loading)
            }, 500)
            
        },
        //进入文章
        read(index, id, type){
            console.log(`用户【${vm.userid}】点击了文章【${id}】`)
            switch (type) {
                case '1': 
                    window.location.href=`./pages/childpages/detail_twdt/index.html?uid=${vm.userid}&id=${id}`
                    break;
                case '2': 
                    window.location.href=`./pages/childpages/detail_tw/index.html?uid=${vm.userid}&id=${id}`
                    break;
                case '3': 
                    window.location.href=`./pages/childpages/detail_wz/index.html?uid=${vm.userid}&id=${id}`
                    break;
                case '4': 
                    window.location.href=`./pages/childpages/detail_xq/index.html?uid=${vm.userid}&id=${id}`
                    break;

            }
            
        },
        //点赞
        like(index, id){
            let type = ""
            switch(this.active){
                case '0':
                    type = "all"
                    break;
                case '1':
                    type = "twdt"
                    break;
                case '2':
                    type = "tw"
                    break;
                case '3':
                    type = "wz"
                    break;
                case '4':
                    type = "xq"
                    break;
                default: 
                    type = type
            }
            let icon = document.querySelector(`.${type} [index='${index}'] .bottom .likes .icon`)
            //禁止点击
            let clickIcon = document.querySelector(`.${type} [index='${index}'] .bottom .likes`)
            clickIcon.style.pointerEvents = 'none'
            if (icon.style.backgroundImage.includes('./img/likes-active.webp')){
                icon.style.background = 'url(./img/likes.webp) no-repeat'
                icon.style.backgroundSize = 'contain'
                //alert("已取消")
            }else{
                icon.style.background = 'url(./img/likes-active.webp) no-repeat'
                icon.style.backgroundSize = 'contain'
                //alert("已点赞"+icon.style.backgroundImage)
            }
            
            //console.log(icon)
            console.log(`用户【${vm.userid}】点赞了文章${index}【${id}】`)
            /**/
            let url = `https://fc-mp-e8e2bde5-0c0c-4622-87b5-66f8b08c3856.next.bspapp.com/getArticleList1.0`
            let method = 'likes_RV146VR1468v1r86WRV'
            let data = {
                userid: `${vm.userid}`,
                articleid: id
            }
            axios.post(`${url}/${method}`, data)
            .then(res=>{
                //开启点击
                clickIcon.style.pointerEvents = 'auto'
                console.log(res.data)
                if(res.data.code === 0){//请求成功
                    let likesNum = document.querySelector(`.${type} [index='${index}'] .bottom .likes .likesNum`)
                    if(res.data.data.code === 1){//点赞操作
                        likesNum.innerText = Number(likesNum.innerText)+1
                    }else if(res.data.data.code === -1){//取消点赞操作
                        likesNum.innerText = Number(likesNum.innerText)-1
                        icon.style.background = 'url(./img/likes.webp) no-repeat'
                        icon.style.backgroundSize = 'contain'
                    }
                }else{//请求失败
                    vm.$toast.fail({
                        message: '服务错误',
                        forbidClick: true
                    })
                    let icon = document.querySelector(`.${type} [index='${index}'] .bottom .likes .icon`)
                    if (icon.style.backgroundImage.includes('./img/likes-active.webp')){
                        icon.style.background = 'url(./img/likes.webp) no-repeat'
                        icon.style.backgroundSize = 'contain'
                        //alert("已取消")
                    }else{
                        icon.style.background = 'url(./img/likes-active.webp) no-repeat'
                        icon.style.backgroundSize = 'contain'
                        //alert("已点赞"+icon.style.backgroundImage)
                    }
                }
            })
        },
        //汇报
        report(index, id){
            console.log(`用户【${vm.userid}】汇报了文章【${id}】`)
        },

        //组件
        onRefresh() {
            this.allArticleList = []
            this.page = 1
            //this.getArticles('all', this.page)
            //获取本人喜欢列表
            vm.getLikesRecords()

        },
        showPopup() {
            this.popupShow = true;
        },
        imagePreview(images) {
            this.show = true
            this.images = images
        },
        onChange(index) {
            this.index = index;
        },
        //tab
        onClick(index, title) {
            this.$toast(`${title}`);
            this.getLikesRecords()
            this.page = 1
            this.allArticleList = []
            console.log("【击nav】"+title)
        }
    },
    mounted() {
        
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()+1
        let day = date.getDate()
        this.now = {
            year: year,
            month: month,
            day: day
        }
        /**/
        let userInfo = localStorage.getItem('XGB-user')
        this.userid = JSON.parse(userInfo).id
        this.userImg = (JSON.parse(userInfo).userImg === "") ? "../../images/person/person_senter/defaultUserImg.webp" : JSON.parse(userInfo).userImg
        //this.getArticles('all', this.page)
        let parameter = window.location.search.substring(1).split('=')[1]
        this.searchValue = ""
        if(parameter != undefined){
            let topic = decodeURI(parameter)
            this.searchTopic(topic)
            // return
        }else{
            this.getLikesRecords()
        }
        window.addEventListener('scroll', this.handleScroll, true)



        
        },
    beforeUpdate(){
        console.log("数据改变")
    }
})